package com.renrenyou.duanshipin.net;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketTimeoutException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import okhttp3.ResponseBody;

//create by hulei
public abstract class IFileDownloadCallback implements Callback {

    private final String TAG = "IFileDownloadCallback";
    private final String mFilePath;
    private final Handler mHandler = new Handler(Looper.getMainLooper());

    public IFileDownloadCallback(String filePath) {
        this.mFilePath = filePath;
    }

    @Override
    public void onResponse(Call call, Response response) {
        if (call.isCanceled()) {
            failure(-1, "http has canceled");
            return;
        }

        if (response != null && response.isSuccessful()) {
            ResponseBody body = response.body();
            if (body != null) {
                try {
                    InputStream is = body.byteStream();
                    long totalSize = body.contentLength();

                    File file = new File(mFilePath);
                    if (file.exists()) {
                        file.delete();
                    }
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                    }
                    file.createNewFile();
                    OutputStream os = new FileOutputStream(file, false);
                    int length;
                    long count = 0;
                    byte[] bytes = new byte[1024];

                    onStart();
                    while ((length = is.read(bytes)) != -1) {
                        os.write(bytes, 0, length);
                        count += length;
                        onProgress(count, totalSize);
                    }
                    is.close();
                    os.close();
                    os.flush();

                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            downloadSuccess(file);
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                    failure(response.code(), e.getMessage());
                }
            } else {
                failure(-4, "responseBody is empty");
            }
        } else {
            Log.d(TAG, "网络连接错误！");
            failure(-2, "connect failure");
        }
    }

    @Override
    public void onFailure(Call call, IOException e) {
        if (e instanceof SocketTimeoutException) {
            failure(-3, "connect failure");
        } else {
            failure(-3, e.getMessage());
        }
    }

    abstract public void onStart();

    abstract public void onProgress(long current, long total);

    abstract public void downloadSuccess(File file);

    abstract public void failure(int errorCode, String errorMsg);
}
